let app = new Vue({
    el: '#app',
    data: {
        user: JSON.parse(sessionStorage.getItem('user')),
        // userTaskId:sessionStorage.getItem("userTaskId"),
        exam: JSON.parse(sessionStorage.getItem('exam')),            // 存储试卷数据
        changeCount: sessionStorage.getItem("changeCount"),           // 切屏记录数 
        paperQuestions: [],  // 存储试题数据
        singleCount: 0,    // 记录单选题数量
        multipleCount: 0,  // 记录多选题数量
        judgeCount: 0     // 记录判断题数量        

    },
    created() {
        // 根据试卷信息的试题编号查询试题信息
        $.ajax({
            url: 'http://localhost:8080/paperQuestion/selectById',
            type: 'post',
            data: { questions: this.exam.questions },
            success: function (vo) {
                if (vo.code == 200) {
                    app.paperQuestions = vo.data;
                    app.singleCount = vo.singleCount;
                    app.multipleCount = vo.multipleCount;
                    app.judgeCount = vo.judgeCount;
                    // console.log(app.exam);
                    // console.log(app.paperQuestions);
                    // console.log(app.singleCount);
                    // console.log(app.multipleCount);
                    // console.log(app.judgeCount);


                    // 判断切屏次数是否超过三次，如已达到三次，则直接舞弊0分处理
                    if (app.changeCount >= 3) {
                        layer.open({
                            closeBtn: 0,  // 右上角关闭
                            resize: false,  // 是否允许拉伸
                            move: false,    // 是否允许拖拽
                            title: ['考试违规', 'font-size:18px;color:red'],
                            content: '试卷得分：0分',
                            btn: ['返回考试记录'],
                            yes: function (index, layero) {
                                // 计算考生答卷时间
                                let doTime = null;
                                let djsendtime = $.cookie("djsendtime");                      // 倒计时结束时间
                                if (djsendtime == null || djsendtime == undefined || djsendtime == 'undefined' || djsendtime == 'null') {
                                    doTime = app.exam.suggestTime;
                                } else {
                                    let now = new Date().getTime();                               // 当前时间
                                    let locksecends = parseInt((djsendtime - now) / 1000);        // 剩余时差
                                    doTime = app.exam.suggestTime - locksecends;                  // 答卷时间
                                }

                                let formData = {
                                    'examPaperId': app.exam.examPaperId,
                                    'examPaperName': app.exam.examPaperName,
                                    'paperType': app.exam.paperType,
                                    'subjectName': app.exam.subjectName,
                                    'levelName': app.exam.levelName,
                                    'paperScore': app.exam.paperScore,
                                    'studentScore': 0,
                                    'questionCount': app.exam.questionCount,
                                    'questionCurrent': 0,
                                    'doTime': doTime,
                                    'createUser': app.user.userId,
                                    'userName': app.user.userName,
                                    'createTime': app.exam.createTime,
                                    'status':3  // 舞弊处理
                                }
                                console.log(formData);

                                // 生成答卷结果记录
                                $.ajax({
                                    url: 'http://localhost:8080/examPaperResult/add',
                                    type: 'post',
                                    data: formData,
                                    beforeSend: function () {
                                        loadIndex = layer.load(1, {
                                            shade: [0.5, '#fff'] //0.1透明度的白色背景
                                        });
                                    },
                                    success: function (vo) {
                                        if (vo.code == 200) {

                                            // 添加当前用户的一条日志记录
                                            let formData2 = {
                                                userId: app.user.userId,
                                                userName: app.user.userName,
                                                realName: app.user.realName,
                                                content: "提交试卷《" + app.exam.examPaperName + "》 得分：0 耗时：" + doTime + "秒",
                                            }
                                            $.ajax({
                                                url: 'http://localhost:8080/log/add',
                                                type: 'post',
                                                data: formData2,
                                                success: function (vo2) {
                                                    if (vo2.code == 200) {
                                                        // 清除倒计时的cookie值
                                                        $.cookie("djsendtime", null);
                                                        layer.close(index);
                                                        window.location.replace("exam_record.html");
                                                    }
                                                }
                                            });
                                         
                                        }
                                    }
                                });
                            }
                        });
                        return;
                    }

                    // 判断答卷时间是否已到，如答卷时间已到，则提示提交试卷
                    let djsendtime = $.cookie("djsendtime");
                    if (djsendtime == null || djsendtime == undefined || djsendtime == 'undefined' || djsendtime == 'null') {
                        $("#timeOut").show();
                    }

                }
            }
        });
    },
    updated() {
        layui.use('form', function () {
            let form = layui.form;
            form.render();

        });
    },
    methods: {
        save: function () {
            //询问框
            layer.confirm('您仍有时间答题，确定现在交卷吗?', {
                icon: 3,
                closeBtn: 0,  // 右上角关闭
                resize: false,  // 是否允许拉伸
                move: false,    // 是否允许拖拽
                btn: ['提交', '继续答题'] //按钮
            }, function () {

                submitExamPaper();
            });


        },
        cls: function () {
            $("#timeOut").hide();
            submitExamPaper();
        }
    }

});


/**
 * 计算考生答卷，生成对应答卷与错题
 */
function submitExamPaper() {
    // 定义一个数组，用于存放考生的答卷答案
    let arr = [];

    // 获取考生的单选题答案
    for (let i = 0; i < app.singleCount; i++) {
        let newName = "questionSingle" + i;
        let single = $("input[name='" + newName + "']:checked").val();
        // 判断考生是否选择答案
        if (single != null) {
            arr.push(single);
        } else {
            arr.push("");
        }
    }

    // 获取考生的多选题答案
    for (let i = 0; i < app.multipleCount; i++) {
        let newId = app.singleCount + 1 + i;
        let multiple = '';
        $("#" + newId + " input:checkbox[name='questionMultiple']:checked").each(function () {
            multiple = multiple + $(this).val() + "&";
        });
        // 去除最后一个"&"字符 及判断考生是否选择答案
        if (multiple.length > 0) {
            multiple = multiple.substr(0, multiple.length - 1);
            arr.push(multiple);
        } else {
            arr.push("");
        }
    }

    // 获取考生的判断题答案
    for (let i = 0; i < app.judgeCount; i++) {
        let newName = "questionJudge" + i;
        let judge = $("input[name='" + newName + "']:checked").val();
        // 判断考生是否选择答案
        if (judge != null) {
            arr.push(judge);
        } else {
            arr.push("");
        }
    }

    // 存放所有试题的正确答案
    let arr2 = [];
    // 存放所有试题ID
    let arr3 = [];
    // 存放所有试题的题型
    let arr4 = [];
    // 存放所有试题的分数
    let arr5 = [];

    for (let i = 0; i < app.paperQuestions.length; i++) {
        arr2.push(app.paperQuestions[i].correctAnswer);
        arr3.push(app.paperQuestions[i].paperQuestionId);
        arr4.push(app.paperQuestions[i].questionType);
        arr5.push(app.paperQuestions[i].score);
    }

    // 统计考生的正确题数以及总得分
    let realCount = 0;
    let scores = 0;
    for (let i = 0; i < app.paperQuestions.length; i++) {
        if (app.paperQuestions[i].correctAnswer == arr[i]) {
            realCount = realCount + 1;
            scores = scores + app.paperQuestions[i].score;
        }
    }

    // 计算考生答卷时间
    let doTime = null;
    let djsendtime = $.cookie("djsendtime");                      // 倒计时结束时间
    if (djsendtime == null || djsendtime == undefined || djsendtime == 'undefined' || djsendtime == 'null') {
        doTime = app.exam.suggestTime;
    } else {
        let now = new Date().getTime();                               // 当前时间
        let locksecends = parseInt((djsendtime - now) / 1000);        // 剩余时差
        doTime = app.exam.suggestTime - locksecends;                  // 答卷时间
    }

    console.log(arr);   //考生答案
    console.log(arr2);  //正确答案
    console.log(arr3);  //试题ID
    console.log(arr4);  //试题题型
    console.log(arr5);  //试题分数
    console.log("正确题数：" + realCount);
    console.log("考生得分：" + scores);
    console.log("答卷时间（秒）：" + doTime);

    let formData = {
        'examPaperId': app.exam.examPaperId,
        'examPaperName': app.exam.examPaperName,
        'paperType': app.exam.paperType,
        'subjectName': app.exam.subjectName,
        'levelName': app.exam.levelName,
        'paperScore': app.exam.paperScore,
        'studentScore': scores,
        'questionCount': app.exam.questionCount,
        'questionCurrent': realCount,
        'doTime': doTime,
        'createUser': app.user.userId,
        'userName': app.user.userName,
        'createTime': app.exam.createTime
    }
    console.log(formData);


    /**
     * 生成考生的答卷结果记录
     */
    $.ajax({
        url: 'http://localhost:8080/examPaperResult/add',
        type: 'post',
        data: formData,
        success: function (vo) {
            if (vo.code == 200) {
                // 获取生成的答卷结果ID
                console.log(vo.data);

                let formData2 = {
                    stuAnswer: arr,          //学生做题答案
                    realAnswer: arr2,        //试题正确答案
                    paperQuestionIds: arr3,  //试题ID
                    questionTypes: arr4,     //试题题型
                    scores: arr5,            //试题分数
                    examPaperResultId: vo.data, //答卷结果ID
                    subjectName: app.exam.subjectName,
                    levelName: app.exam.levelName,
                    examPaperName:app.exam.examPaperName,
                    createUser: app.user.userId
                }
                let loadIndex = null;
                $.ajax({
                    url: 'http://localhost:8080/errorQuestion/add',
                    type: 'post',
                    data: formData2,
                    dataType: 'json',
                    traditional: true, //解决ajax异步请求传数组参数，后台接收为null的问题
                    beforeSend: function () {   // 请求成功前的加载过渡
                        loadIndex = layer.load(1, {
                            shade: [0.5, '#fff'] //0.1透明度的白色背景
                        });
                    },
                    success: function (vo2) {
                        if (vo2.code == 200) {
                            // 关闭加载层
                            // layer.close(loadIndex);
                            layer.open({
                                // skin: 'layui-layer-lan',  // 样式
                                // icon:6,    // 图标
                                closeBtn: 0,  // 右上角关闭
                                resize: false,  // 是否允许拉伸
                                move: false,    // 是否允许拖拽
                                title: ['考试结果', 'font-size:18px'],
                                content: '试卷得分：' + scores + '分',
                                btn: ['返回考试记录'],
                                yes: function (index, layero) {
                                    // 添加当前用户的一条日志记录
                                    let formData3 = {
                                        userId: app.user.userId,
                                        userName: app.user.userName,
                                        realName: app.user.realName,
                                        content: "提交试卷《" + app.exam.examPaperName + "》 得分：" + scores + " 耗时：" + doTime + "秒",
                                    }
                                    $.ajax({
                                        url: 'http://localhost:8080/log/add',
                                        type: 'post',
                                        data: formData3,
                                        success: function (vo3) {
                                            if (vo3.code == 200) {
                                                // 清除倒计时的cookie值
                                                $.cookie("djsendtime", null);
                                                layer.close(index);
                                                window.location.replace("exam_record.html");
                                            }
                                        }
                                    });

                                }
                            });
                        }
                    }
                });

            }
        }
    });
}








